package com.tskj.leonsu.service;

import com.alibaba.fastjson.JSONObject;
import com.tskj.leonsu.db.redis.util.RedisUtil;
import com.tskj.leonsu.service.ad.AdService;
import com.tskj.leonsu.service.task.SystemTask;
import com.tskj.leonsu.utility.Tools;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ResourceBundle;

/**
 * @author LeonSu
 */
@Service
public class LoginService {

    @Autowired
    private AdService adService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private GyglService gyglService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private SystemTask systemTask;

    private Boolean runDemo;
    public LoginService() {
        ResourceBundle res = ResourceBundle.getBundle("config.system.system");
        runDemo = res.containsKey("runDemo") && "1".equalsIgnoreCase(res.getString("runDemo").trim());
//        System.out.println(adHost);
    }

    private JSONObject getDemoStudentInfo(String userName, String password) {
        JSONObject ret = new JSONObject();
        ret.put("code", 0);
        ret.put("displayName", "测试帐号");
        ret.put("sAMAccountName", "12345");
        return ret;
    }

    public JSONObject login(String userName, String password) {
        return login(userName, password, false);
    }

    public JSONObject login(String userName, String password, Boolean nologin) {
        int loginResult = 0;
        if (!runDemo) {
            loginResult = adService.adLogin(userName, password);
        }
        JSONObject ret = new JSONObject();
        switch (loginResult) {
            case 0:
                JSONObject student = new JSONObject();
                JSONObject student_ad;
                if (!runDemo) {
                    student_ad = adService.getADUserInfo(userName, password);
                } else {
                    student_ad = getDemoStudentInfo(userName, password);
                }
                // 姓名
                String studentName;
                // 学号
                String studentNo;
                String studentIdCard;
                if (student_ad != null) {
                    System.out.println(student_ad.toJSONString());
                    studentName = student_ad.getString("displayName");
                    studentNo = student_ad.getString("sAMAccountName");
                    if (student_ad.containsKey("description") && !StringUtils.isEmpty(student_ad.getString("description"))) {
                        studentIdCard = student_ad.getString("description");
                    } else {
                        studentIdCard = "";
                    }
                } else {
                    studentName = "";
                    studentNo = userName;
                    ret.put("code", 1);
                    ret.put("errMsg", "登录时出现错误，未获取信息");
                    return ret;
                }
                // 根据学号从公寓系统中获取学生信息
                JSONObject studentInfo = gyglService.getStudentInfo(studentName, studentNo, studentIdCard);
                String studentSex = studentInfo.getString("sex");
                String xueYuan = studentInfo.getString("xueyuan");
                studentName = studentInfo.getString("studentname");

                if (!studentService.exists(userName)) {
                    if (!studentService.insertStudentInfo(userName, studentName, studentNo, studentSex,  xueYuan, 0)) {
                        ret.put("code", 1);
                        ret.put("errMsg", "登录时出现错误，请稍候重试");
                        return ret;
                    }
                }
                student.put("studentName", studentName);
                student.put("studentNo", studentNo);
                student.put("sex", studentSex);
                student.put("xueyuan", xueYuan);
                student.put("needCheck", studentService.getStatus(userName) != 1);
                ret.put("code", 0);
                ret.put("data", student);
                String shortToken = createShortToken(userName);
                ret.put("noLoginToken", saveToRedis(userName, shortToken));
                ret.put("token", shortToken);
                return ret;
            case 2:
                ret.put("errMsg", "用户不存在");
                break;
            case 3:
                ret.put("errMsg", "密码错误");
                break;
            case 4:
                ret.put("errMsg", "教师登陆");
                break;
            case 1:
            default:
                ret.put("errMsg", "未知错误");
        }
        ret.put("code", 1);
        return ret;
    }

    private void saveStudent(JSONObject obj) {

    }
    /**
     * 如果用户选择30天（含当天）免登录，则创建一个长效token
     * @param adUserName 学生AD帐号
     * @return
     */
    public String saveToRedis(String adUserName, String shortToken) {
        String longToken = Tools.newId();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime endDateTime = LocalDateTime.parse(Tools.getAddDate(now, 29) + "T23:59:59");
        java.time.Duration duration = java.time.Duration.between(now,  endDateTime);
        JSONObject userInfo = new JSONObject();
        userInfo.put("adUserName", adUserName);
        userInfo.put("token", shortToken);
        redisUtil.set(longToken, userInfo, duration.getSeconds());
        return longToken;
    }

    /**
     * 创建一个临时token，有效期到当天午夜24点
     * @param adUserName 学生AD帐号
     * @return
     */
    public String createShortToken(String adUserName) {
        String shortToken = Tools.newId();
        LocalDateTime middleNight = LocalDateTime.parse(Tools.today() + "T23:59:59");
        java.time.Duration duration = java.time.Duration.between(LocalDateTime.now(),  middleNight);
        redisUtil.set(shortToken, adUserName, duration.getSeconds());
        return shortToken;
    }

    public String getAdUserName(String token) {
        Object value = redisUtil.get(token);
        if (value != null) {
            return value.toString();
        }
        return "";
    }

    public JSONObject checkLongToken(String longToken) {
        if (!redisUtil.hasKey("meals")) {
            systemTask.loadRestaurantToRedisNow();
        }
        JSONObject ret = new JSONObject();
        JSONObject userInfo = (JSONObject) redisUtil.get(longToken);
        System.out.println(longToken + "=" + userInfo.toJSONString());
        String adUserName = userInfo.getString("adUserName");
        String shortToken = userInfo.getString("token");
        if (adUserName == null) {
            ret.put("code", 1);
            ret.put("errMsg", "登录过期，请重新登录");
            return ret;
        }
        if (!redisUtil.hasKey(shortToken)) {
            shortToken = createShortToken(adUserName);
            userInfo.put("token", shortToken);
            redisUtil.set(longToken, userInfo);
        }
        ret.put("code", 0);
        ret.put("token", shortToken);
        JSONObject student_tmp = studentService.getStudentInfo(adUserName.toString());
        JSONObject student = new JSONObject();
        student.put("studentName", student_tmp.getString("studentname"));
        student.put("studentNo", student_tmp.getString("studentid"));
        student.put("sex", student_tmp.getString("sexy"));
        student.put("xueyuan", student_tmp.getString("xueyuan"));
        student.put("needCheck", studentService.getStatus(adUserName.toString()) != 1);
        ret.put("data", student);

        return ret;
    }
}
